package net.techwatch.guava.io;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Utility class for File usage.
 *
 */
public final class Files {

	private final static int BUF_SIZE = 4096;

	private Files() {
		// nothing to do
	}

	/**
	 * Read a file content and return it as a byte array. IO closing exception
	 * are not thrown.
	 * 
	 * @param file
	 *            file to read
	 * @return a byte array representation of the file content
	 * @throws IOException
	 *             any exception thrown by IO streams
	 */
	public static byte[] toByteArray(File file) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		InputStream in = new FileInputStream(file);
		try {
			byte[] buf = new byte[BUF_SIZE];
			while (true) {
				int r = in.read(buf);
				if (r == -1)
					break;
				out.write(buf, 0, r);
			}
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				// WARNING: IOException thrown while closing
			}
		}
		return out.toByteArray();
	}
}
